Volley学习(二)简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json

您所在的位置:网站首页 json 请求头 Volley学习(二)简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json

Volley学习(二)简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json

#Volley学习(二)简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json| 来源: 网络整理| 查看: 265

,然后在deliverResponse去外部提供接口,更新页面之类的

我们看看这代码,很显然没有做到如何进行对返回的数据,比如Json格式的数据,进行进一步的封装为对象,考虑到封装对象有

fastson、Gson、还有JsonReader都可以,我这篇博客是用的Gson来进行解析json的,主要是方便了代码,毕竟Gson也是谷歌出的。

package com.example.saflyvolley; import java.io.UnsupportedEncodingException; import android.util.Log; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; import com.example.saflyvolley.safinterface.UIDataListener; import com.google.gson.Gson; public class SaflyBaseRequest extends Request { private Gson mGson; private final Listener mListener; private Class mClass; public SaflyBaseRequest(int method, String url, Class clazz, Listener listener, ErrorListener errorListener) { super(method, url, errorListener); mGson = new Gson(); mClass = clazz; mListener = listener; } /** * 默认get方式 */ public SaflyBaseRequest(String url, Class clazz, Listener listener, ErrorListener errorListener) { this(Method.GET, url, clazz, listener, errorListener); } @Override protected Response parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); Log.i("Safly", "jsonString-->>"+jsonString); return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { mListener.onResponse(response); } } 以上的代码是从网上搜的,也是很好理解,在SaflyBaseRequest构造器中,除了父类的几个参数保持不动外 mGson = new Gson(); mClass = clazz; 这是新增的,在parseNetworkResponse中 return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response)); 将原始的,替换为上面的,意思就是将封装好的对象,提供给外部接口使用 parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 接下来就看谷歌原生的那种get、post请求

下面这行代码是一个Json数据的接口

http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly 返回类型如下,我们就用这个进行get、post请求(添加参数) { "resultcode": "101", "reason": "错误的请求KEY!", "result": null, "error_code": 10001 }

我们对此创建对象,以及set get方法(省略了)

private String resultcode; private String reason; private String result; private int error_code; 我们获取到json封装好的对象后,可能去某个界面进行填充listview啊之类的,所以说我们可以在onResponse中在制造一个接口,进行主界面的回调使用,如果某个界面获取json之后返回对象A,如果在请求其他的Json返回对象B,所以我们可以做一个泛型接口 public interface UIDataListener { public void onErrorHappened(String errorMessage); public void onDataChanged(T data); } public void onResponse(ResponseMsg responseMsg) { if (uiResponseMsgDataListener != null) { notifyDataChanged(responseMsg); } } protected void notifyDataChanged(T data) { if (uiResponseMsgDataListener != null) { if (data instanceof ResponseMsg) { uiResponseMsgDataListener.onDataChanged((ResponseMsg) data); } } } 上面是一个泛型方法,可以对多种返回的json封装对象进行通知界面实现方法

然后在主界面进行接口回调即可

/** * 封装完毕后的监听,设置界面 */ @Override public void onDataChanged(ResponseMsg responseMsg) { Log.i("Safly", "" + responseMsg.getError_code()); Log.i("Safly", "" + responseMsg.getReason()); Log.i("Safly", "" + responseMsg.getResult()); Log.i("Safly", "" + responseMsg.getResultcode()); }

我们在看下Post方式,进行添加params-->>phone=13429667914&key=safly

http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly SaflyRequestController saflyRequestController = new SaflyRequestController(); Map map = new HashMap(); map.put("phone", "13429667914"); map.put("key", "safly"); saflyRequestController.RequestType(SaflyRequestController.RequestPost, map); saflyRequestController.setUiDataListener(this);,>,> @Override protected Map getParams() throws AuthFailureError { return map; },> 如下是谷歌的get post的请求log日志(在没有修改请求头、请求体的前提下) 到这里谷歌那些原始的方法就学习完毕了,我之所以写这篇博客,主要就是利用我公司的网络请求跟volley的结合起来,我公司的网络请求代码是封装的httpUrlConnection,代码比较臃肿,所以来利用下volley进行实现

Volley为请求头、请求体添加Json格式的数据

由于下面的代码是不能实现的,我就在定义了一个接口 public class MainActivity extends Activity implements UIDataListener, UIDataListener { 接口如下 public interface UIImplHeadBodyDataListener { public void onErrorHappened(String errorMessage); public void UIImplHeadBodyDataChange(T data); } 我公司的网络请求,是对请求头、请求体做了修改,也是传给服务器的Json格式数据,那么我们就考虑用什么工具或者方法,去进行请求头、体的Json格式封装

Gson、fastson、JsonObject都可以,我们这篇博客用下Gson、JsonObject

Gson根据对象,生成json格式Gson.toJson方法

首先看我公司的传给服务器的Json数据

{ "Request": { "head": { "app_type": "3", "os_type": "android", "osversion": "5.1.1", "appversion": "1.0", "devicefactory": "LGE", "devicemodel": "AOSP on HammerHead" }, "body": { "phoneimei": "353490061934846", "context": "反馈" } } } 我们先来用Gson进行Json格式数据的生成

我们分析那个Json数据,看看需要创建什么样的对象呢?(省略了get 、set方法)

public class RequestBean { private Request Request; public RequestBean() { super(); } public RequestBean(Request request) { super(); this.Request = request; } public Request getRequest() { return Request; } public void setRequest(Request request) { this.Request = request; } // ///////////////HeadHead////////////////// public static class Head { private String app_type; private String os_type; private String osversion; private String appversion; private String devicefactory; private String devicemodel; public Head(String app_type, String os_type, String osversion, String appversion, String devicefactory, String devicemodel) { super(); this.app_type = app_type; this.os_type = os_type; this.osversion = osversion; this.appversion = appversion; this.devicefactory = devicefactory; this.devicemodel = devicemodel; } public Head() { super(); } } ////////////////BodyBody///////////////////// public static class Body { private String phoneimei; private String context; public Body(String phoneimei, String context) { super(); this.phoneimei = phoneimei; this.context = context; } public Body() { super(); // TODO Auto-generated constructor stub } } //////////////////RequestRequest///////////////////////// public static class Request { private Head head; private Body body; public Request(Head head, Body body) { super(); this.head = head; this.body = body; } } } 以上就是对传给服务器的json格式创建的对象

如下就是gson生成的json格式

RequestBean msg = new RequestBean(); RequestBean.Head head = new RequestBean.Head("3", "android", "5.1.1", "1.0", "LGE", "AOSP on HammerHead"); RequestBean.Body body = new RequestBean.Body("353490061934846", "反馈"); RequestBean.Request request = new RequestBean.Request(head, body); msg.setRequest(request); Gson gson = new Gson(); String requestMsg = gson.toJson(msg);

根据JsonObject生成json数据 private String createJson() throws JSONException { JSONObject jsonObject = new JSONObject(); JSONObject body = new JSONObject(); body.put("phoneimei", "353490061934846"); body.put("context", "反馈"); JSONObject head = new JSONObject(); head.put("app_type", "3"); head.put("os_type", "android"); head.put("osversion", "5.1.1"); head.put("appversion", "1.0"); head.put("devicefactory", "LGE"); head.put("devicemodel", "AOSP on HammerHead"); JSONObject Request = new JSONObject(); Request.put("body", body); Request.put("head", head); jsonObject.put("Request", Request); return jsonObject.toString(); } 以上就是2种生成json的方法(当然还有其他的拼接的方式,我这里就举例子了,前几篇有写) 如何为Volley请求头部或者请求体添加json数据 @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap(); headers.put("Charset", "UTF-8"); headers.put("Content-Type", "application/x-javascript"); headers.put("Accept-Encoding", "gzip,deflate"); return headers; } @Override public String getBodyContentType() { return String.format("application/x-www-form-urlencoded; charset=%s", "utf-8"); } @Override public byte[] getBody() throws AuthFailureError { // TODO Auto-generated method stub return requestStringBytes; },>,>,> 我对volley研究的不够深入,我也是搜资料,才知道getBodyContentType这个方法内,才可以获取成功,或许就是格式的问题吧

以下是我公司的返回的json,

{"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}} 以下就是针对返回的json数据,进行的对象封装 package com.example.saflyvolley.bean; /** * onResponse {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}} * */ public class ResponseBean { private Response Response; public ResponseBean() { super(); } public ResponseBean(Response response) { super(); this.Response = response; } public Response getResponse() { return Response; } public void setResponse(Response response) { this.Response = response; } // ///////////////////////////// public static class Response { private Head head; public Head getHead() { return head; } public void setHead(Head head) { this.head = head; } public Response(Head head) { super(); this.head = head; } } // onResponse // {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}} public static class Head { private String statuscode; private String statusmsg; public String getStatuscode() { return statuscode; } public void setStatuscode(String statuscode) { this.statuscode = statuscode; } public String getStatusmsg() { return statusmsg; } public void setStatusmsg(String statusmsg) { this.statusmsg = statusmsg; } public Head(String statuscode, String statusmsg) { super(); this.statuscode = statuscode; this.statusmsg = statusmsg; } public Head() { super(); } } }

以上就是volley的封装,生成json,然后重写请求头体,然后封装对象,以下是代码区

#################################代码区 代码区 代码区############################

SaflyApplication

package com.example.saflyvolley; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.telephony.TelephonyManager; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class SaflyApplication extends Application { private TelephonyManager telephonyManager; private static RequestQueue requestQueue; private static SaflyApplication instance; @Override public void onCreate() { super.onCreate(); this.instance = this; requestQueue = Volley.newRequestQueue(getApplicationContext()); initHttps(); } public static SaflyApplication getInstance() { return instance; } public static RequestQueue getRequestQueue() { return requestQueue; } private void initHttps() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); trustStore.load(null, null); SSLSocketFactoryEx sf = new SSLSocketFactoryEx(trustStore); HttpsURLConnection.setDefaultSSLSocketFactory(sf.getSSLContext() .getSocketFactory()); HttpsURLConnection .setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { } } static class SSLSocketFactoryEx extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } public SSLContext getSSLContext() { return sslContext; } } } SaflyBaseRequest package com.example.saflyvolley; import java.io.UnsupportedEncodingException; import android.util.Log; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; import com.example.saflyvolley.safinterface.UIDataListener; import com.google.gson.Gson; public class SaflyBaseRequest extends Request { private Gson mGson; private final Listener mListener; private Class mClass; public SaflyBaseRequest(int method, String url, Class clazz, Listener listener, ErrorListener errorListener) { super(method, url, errorListener); mGson = new Gson(); mClass = clazz; mListener = listener; } /** * 默认get方式 */ public SaflyBaseRequest(String url, Class clazz, Listener listener, ErrorListener errorListener) { this(Method.GET, url, clazz, listener, errorListener); } @Override protected Response parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); Log.i("Safly", "jsonString-->>"+jsonString); return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { mListener.onResponse(response); } } 看volley原生的get、post代码

ResponseMsg

package com.example.saflyvolley.bean; //{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001} public class ResponseMsg { private String resultcode; private String reason; private String result; private int error_code; public String getResultcode() { return resultcode; } public void setResultcode(String resultcode) { this.resultcode = resultcode; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public ResponseMsg() { super(); } public ResponseMsg(String resultcode, String reason, String result, int error_code) { super(); this.resultcode = resultcode; this.reason = reason; this.result = result; this.error_code = error_code; } } UIDataListener package com.example.saflyvolley.safinterface; public interface UIDataListener { public void onErrorHappened(String errorMessage); public void onDataChanged(T data); }

SaflyRequestController

package com.example.saflyvolley; import java.util.HashMap; import java.util.Map; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request.Method; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.example.saflyvolley.bean.ResponseBean; import com.example.saflyvolley.bean.ResponseMsg; import com.example.saflyvolley.safinterface.UIDataListener; public class SaflyRequestController { public static final int RequestGet = 1; public static final int RequestPost = 2; public static final String stringUrlNoParams = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly"; public static final String stringUrlWithParams = "http://apis.juhe.cn/mobile/get?"; /** * 封装对象完毕的接口监听 */ private UIDataListener uiResponseMsgDataListener; public void setUiDataListener( UIDataListener uiResponseMsgDataListener) { this.uiResponseMsgDataListener = uiResponseMsgDataListener; } protected void notifyDataChanged(T data) { if (uiResponseMsgDataListener != null) { if (data instanceof ResponseMsg) { uiResponseMsgDataListener.onDataChanged((ResponseMsg) data); } } } protected void notifyErrorHappened(String errorMessage) { if (uiResponseMsgDataListener != null) { uiResponseMsgDataListener.onErrorHappened(errorMessage); } } /** * 請求方式 */ public void RequestType(int getRequestType, final Map map) { SaflyBaseRequest request; switch (getRequestType) { // GET請求 case RequestGet: request = new SaflyBaseRequest(Method.GET, stringUrlNoParams, ResponseMsg.class, new Listener() { @Override public void onResponse(ResponseMsg responseMsg) { if (uiResponseMsgDataListener != null) { notifyDataChanged(responseMsg); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (uiResponseMsgDataListener != null) { String message = volleyError.getMessage(); Log.i("Safly", "message-->>" + message); notifyErrorHappened(message); } } }); SaflyApplication.getRequestQueue().add(request); break; // POST請求 case RequestPost: request = new SaflyBaseRequest(Method.POST, stringUrlWithParams, ResponseMsg.class, new Listener() { @Override public void onResponse(ResponseMsg responseMsg) { if (uiResponseMsgDataListener != null) { notifyDataChanged(responseMsg); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (uiResponseMsgDataListener != null) { String message = volleyError.getMessage(); Log.i("Safly", "message-->>" + message); notifyErrorHappened(message); } } }) { @Override protected Map getParams() throws AuthFailureError { return map; } }; SaflyApplication.getRequestQueue().add(request); break; default: break; } } } ,>,> 接下来看封装请求头、请求体的代码

RequestBean

package com.example.saflyvolley.bean; /** * {"Request": { "head": { "app_type": "3", "os_type": "android", "osversion": * "5.1.1", "appversion": "1.0", "devicefactory": "LGE", "devicemodel": * "AOSP on HammerHead" }, "body": { "phoneimei": "353490061934846", "context": * "反馈" } } } */ public class RequestBean { private Request Request; public RequestBean() { super(); } public RequestBean(Request request) { super(); this.Request = request; } public Request getRequest() { return Request; } public void setRequest(Request request) { this.Request = request; } // ///////////////////////////////// public static class Head { private String app_type; private String os_type; private String osversion; private String appversion; private String devicefactory; private String devicemodel; public String getApp_type() { return app_type; } public void setApp_type(String app_type) { this.app_type = app_type; } public String getOs_type() { return os_type; } public void setOs_type(String os_type) { this.os_type = os_type; } public String getOsversion() { return osversion; } public void setOsversion(String osversion) { this.osversion = osversion; } public String getAppversion() { return appversion; } public void setAppversion(String appversion) { this.appversion = appversion; } public String getDevicefactory() { return devicefactory; } public void setDevicefactory(String devicefactory) { this.devicefactory = devicefactory; } public String getDevicemodel() { return devicemodel; } public void setDevicemodel(String devicemodel) { this.devicemodel = devicemodel; } public Head(String app_type, String os_type, String osversion, String appversion, String devicefactory, String devicemodel) { super(); this.app_type = app_type; this.os_type = os_type; this.osversion = osversion; this.appversion = appversion; this.devicefactory = devicefactory; this.devicemodel = devicemodel; } public Head() { super(); // TODO Auto-generated constructor stub } } public static class Body { private String phoneimei; private String context; public Body(String phoneimei, String context) { super(); this.phoneimei = phoneimei; this.context = context; } public Body() { super(); // TODO Auto-generated constructor stub } public String getPhoneimei() { return phoneimei; } public void setPhoneimei(String phoneimei) { this.phoneimei = phoneimei; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } } public static class Request { private Head head; private Body body; public Request(Head head, Body body) { super(); this.head = head; this.body = body; } public Head getHead() { return head; } public void setHead(Head head) { this.head = head; } public Body getBody() { return body; } public void setBody(Body body) { this.body = body; } } } ResponseBean package com.example.saflyvolley.bean; /** * onResponse {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}} * */ public class ResponseBean { private Response Response; public ResponseBean() { super(); } public ResponseBean(Response response) { super(); this.Response = response; } public Response getResponse() { return Response; } public void setResponse(Response response) { this.Response = response; } // ///////////////////////////// public static class Response { private Head head; public Head getHead() { return head; } public void setHead(Head head) { this.head = head; } public Response(Head head) { super(); this.head = head; } } // onResponse // {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}} public static class Head { private String statuscode; private String statusmsg; public String getStatuscode() { return statuscode; } public void setStatuscode(String statuscode) { this.statuscode = statuscode; } public String getStatusmsg() { return statusmsg; } public void setStatusmsg(String statusmsg) { this.statusmsg = statusmsg; } public Head(String statuscode, String statusmsg) { super(); this.statuscode = statuscode; this.statusmsg = statusmsg; } public Head() { super(); } } } UIImplHeadBodyDataListener package com.example.saflyvolley.safinterface; public interface UIImplHeadBodyDataListener { public void onErrorHappened(String errorMessage); public void UIImplHeadBodyDataChange(T data); } SaflyRequestImplHeadOrBodyController package com.example.saflyvolley; import java.util.HashMap; import java.util.Map; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request.Method; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.example.saflyvolley.bean.ResponseBean; import com.example.saflyvolley.safinterface.UIDataListener; import com.example.saflyvolley.safinterface.UIImplHeadBodyDataListener; public class SaflyRequestImplHeadOrBodyController { private String url = "https://www.imlianxi.com:xxxx/AppFeedback"; /** * 封装对象完毕的接口监听 */ private UIImplHeadBodyDataListener uiResponseBeanDataListener; public void setUIImplHeadBodyDataListener(UIImplHeadBodyDataListener uiResponseBeanDataListener) { this.uiResponseBeanDataListener = uiResponseBeanDataListener; } protected void notifyDataChanged(T data) { if (uiResponseBeanDataListener != null) { if (data instanceof ResponseBean) { uiResponseBeanDataListener.UIImplHeadBodyDataChange((ResponseBean) data); } } } protected void notifyErrorHappened(String errorMessage) { if (uiResponseBeanDataListener != null) { uiResponseBeanDataListener.onErrorHappened(errorMessage); } } /** *封装头部 体部 post方式 */ public void RequestTypeWithRequestHeadAndBody(final byte[] requestStringBytes) { SaflyBaseRequest request; request = new SaflyBaseRequest( Method.POST, url, ResponseBean.class, new Listener() { @Override public void onResponse(ResponseBean responseBean) { if (uiResponseBeanDataListener != null) { notifyDataChanged(responseBean); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (uiResponseBeanDataListener != null) { String message = volleyError.getMessage(); Log.i("Safly", "message-->>" + message); notifyErrorHappened(message); } } }) { @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap(); headers.put("Charset", "UTF-8"); headers.put("Content-Type", "application/x-javascript"); headers.put("Accept-Encoding", "gzip,deflate"); return headers; } @Override public String getBodyContentType() { return String.format("application/x-www-form-urlencoded; charset=%s", "utf-8"); } @Override public byte[] getBody() throws AuthFailureError { // TODO Auto-generated method stub return requestStringBytes; } }; SaflyApplication.getRequestQueue().add(request); } } ,>,>,> 最后看主界面 package com.example.saflyvolley; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.util.Log; import com.example.saflyvolley.bean.RequestBean; import com.example.saflyvolley.bean.ResponseBean; import com.example.saflyvolley.bean.ResponseMsg; import com.example.saflyvolley.safinterface.UIDataListener; import com.example.saflyvolley.safinterface.UIImplHeadBodyDataListener; import com.google.gson.Gson; /** * {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001} */ /** {"Request": { "head": { "app_type": "3", "os_type": "android", "osversion": "5.1.1", "appversion": "1.0", "devicefactory": "LGE", "devicemodel": "AOSP on HammerHead" }, "body": { "phoneimei": "353490061934846", "context": "反馈" } } } */ public class MainActivity extends Activity implements UIDataListener, UIImplHeadBodyDataListener { private String createJson; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * post請求 */ SaflyRequestController saflyRequestController = new SaflyRequestController(); Map map = new HashMap(); map.put("phone", "13429667914"); map.put("key", "safly"); saflyRequestController.RequestType(SaflyRequestController.RequestPost, map); saflyRequestController.setUiDataListener(this); /** * get請求 */ saflyRequestController.RequestType(SaflyRequestController.RequestGet, null); /** * 重寫header body * 利用Gson生成Json格式请求服务器 */ RequestBean msg = new RequestBean(); RequestBean.Head head = new RequestBean.Head("3", "android", "5.1.1", "1.0", "LGE", "AOSP on HammerHead"); RequestBean.Body body = new RequestBean.Body("353490061934846", "反馈"); RequestBean.Request request = new RequestBean.Request(head, body); msg.setRequest(request); Gson gson = new Gson(); String requestMsg = gson.toJson(msg); byte[] requestStringBytes = null; try { requestStringBytes = requestMsg.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Log.i("Safly", "Gson str:" + requestMsg); SaflyRequestImplHeadOrBodyController saflyRequestImplHeadOrBodyController = new SaflyRequestImplHeadOrBodyController(); saflyRequestImplHeadOrBodyController .RequestTypeWithRequestHeadAndBody(requestStringBytes); saflyRequestImplHeadOrBodyController .setUIImplHeadBodyDataListener(this); /** * 利用JsonObject生成json请求服务器 */ try { createJson = createJson(); } catch (JSONException e) { e.printStackTrace(); } String requestMsgByJsonObject = createJson; Log.i("Safly", "JsonObject str:" + requestMsgByJsonObject); } private String createJson() throws JSONException { JSONObject jsonObject = new JSONObject(); JSONObject body = new JSONObject(); body.put("phoneimei", "353490061934846"); body.put("context", "反馈"); JSONObject head = new JSONObject(); head.put("app_type", "3"); head.put("os_type", "android"); head.put("osversion", "5.1.1"); head.put("appversion", "1.0"); head.put("devicefactory", "LGE"); head.put("devicemodel", "AOSP on HammerHead"); JSONObject Request = new JSONObject(); Request.put("body", body); Request.put("head", head); jsonObject.put("Request", Request); return jsonObject.toString(); } /** * 封装完毕后的监听,设置界面 */ @Override public void onDataChanged(ResponseMsg responseMsg) { Log.i("Safly", "" + responseMsg.getError_code()); Log.i("Safly", "" + responseMsg.getReason()); Log.i("Safly", "" + responseMsg.getResult()); Log.i("Safly", "" + responseMsg.getResultcode()); } /** * 服务器返回失败的监听 */ @Override public void onErrorHappened(String errorMessage) { } @Override public void UIImplHeadBodyDataChange(ResponseBean data) { Log.i("Safly", "" + data.getResponse().getHead().getStatuscode()); Log.i("Safly", "" + data.getResponse().getHead().getStatusmsg()); } } ,>,>


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3